const { app, protocol, BrowserWindow } = require('electron')
const path = require('path')

let win = null
app.whenReady().then(()=>{
    createWindow()
})

function createWindow() {
    win = new BrowserWindow({
        width: 1200,
        height: 800,
        webPreferences: {
            webviewTag: true // 开启webview标签
          }
    })

    win.loadFile(path.join(__dirname,'../renderer/index.html'))
    win.webContents.openDevTools({mode: 'bottom'})
    interceptStringProtocol()
    registerHttpProtocol()
}

/* 协议拦截 */ 
// 协议拦截，string响应
function interceptStringProtocol() {
    protocol.interceptStringProtocol('http', (request, callback) => {
        callback({
            mimeType: 'application/json',
            data: JSON.stringify({ name: 'electron' }),
        })
    })
}

/**
 * 处理 <img src="./img/bananas.jpg" /> 中的本地资源
 * 提取路径，映射到 https://img.zlib.cn/bananas.jpg
 * 文件存在则使用，否则下载到本地
 */

function interceptFileProtocol() {
    const fileProtocol = protocol.interceptFileProtocol('file', (request, callback) => {
        if (request.url.includes('img/')) {
            const filename = request.url.split('/').pop()
            const filePath = path.join(__dirname, 'img', filename)
            if (fs.existsSync(filePath)) return callback(filePath)
            const file = fs.createWriteStream(filePath)
            const fileURL = 'https://img.zlib.cn/' + filename
            https.get(fileURL, (res) => {
            res.pipe(file)
            file.on('finish', () => callback(filePath))
            })
        } else {
            const filePath = url.fileURLToPath(request.url)
            callback(filePath)
        }
    })
}

/* 注册协议 */ 
function registerHttpProtocol() {
    protocol.registerHttpProtocol('hello', (request, callback) => {
        const relativePath = request.url.split('/').pop()
        callback({
            url: `https://img.zlib.cn/${relativePath}`,
            method: 'GET',
        })
    })
}
function registerFileProtocol() {
    protocol.registerFileProtocol('cached', (request, callback) => {
        if (request.url.includes('img/')) {
          const filename = request.url.split('/').pop()
          const filePath = path.join(__dirname, 'img', filename)
          if (fs.existsSync(filePath)) return callback(filePath)
          const file = fs.createWriteStream(filePath)
          const fileURL = 'https://img.zlib.cn/' + filename
          https.get(fileURL, (res) => {
            res.pipe(file)
            file.on('finish', () => callback(filePath))
          })
        } else {
          const filePath = url.fileURLToPath(request.url)
          callback(filePath)
        }
    })
}
